
import {
  wx_appid,
  wx_secret,
  wx_api
} from '../setting'

import {
  get,
  post
} from 'request'

export class WXAPI {
  constructor(){

  }


  /**
   * 校验文本合法性
   * @param content
   * @param wx_user
   * @returns
   */
  async msgSecCheck(content: string,wx_user: string){
    let accessToken = await this.getAccessToken()
    return new Promise((resolve,reject) => {
      const requestData = {
        content:content,
        version:2,
        scene:2,
        openid:wx_user,
      }
      post({
        url: `${wx_api}/wxa/msg_sec_check?access_token=${accessToken}`,
        method: "POST",
        json: true,
        headers: {
          "content-type": "application/json",
        },
        body: requestData
      }, async function(error, response, body) {
        if (!error && response.statusCode == 200) {
          console.log(body,'token')
          let tokenResult = typeof(body) === 'string' ? JSON.parse(body) : body
          if(tokenResult){
            resolve(tokenResult)
          }
        }
      })
    })
  }

  /**
   * 获取access-token
   * @returns
   */
  getAccessToken(){
    return new Promise((resolve,reject) => {
      get(`${wx_api}/cgi-bin/token?grant_type=client_credential&appid=${wx_appid}&secret=${wx_secret}`,async (error, response, body) => {
        if (!error && response.statusCode == 200) {
          console.log(body,'token')
          let tokenResult = JSON.parse(body)
          if(tokenResult?.access_token){
            resolve(tokenResult.access_token)
          }else{
            resolve('')
          }
        }else{
          resolve('')
        }
      })
    })
  }
}
